package com.xyz.eduservice.controller;

import com.xyz.entity.R;
import com.xyz.eduservice.entity.vo.SubjectNestedVo;
import com.xyz.eduservice.service.EduSubjectService;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 课程科目 前端控制器
 * @author zsr
 * @since 2021-06-10
 */
@Schema(description="课程分类管理")
@RestController
//@CrossOrigin
@RequestMapping("/eduservice/subject")
@Slf4j
public class EduSubjectController {

    @Autowired
    private EduSubjectService subjectService;

    //获取excel表格 读取内容加载到数据库
    @Schema(description = "添加课程分类")
    @PostMapping("addSubject")
    @CacheEvict(value = "eduSubject",allEntries=true)//清空
    public R addSubject(MultipartFile file){
        subjectService.saveSubject(file, subjectService);
        return R.ok();
    }

    @Schema(description = "课程分类列表[树形]")
    @GetMapping("getSubject")
    public R getSubject(){
        log.info("获取课程分类列表");
        List<SubjectNestedVo> list = subjectService.getAllSubject();
        return R.ok().data(list);
    }

    // 新增插入方法
    @Schema(description = "添加单个课程分类")
    @PostMapping("addOnSubject")
    @CacheEvict(value = "eduSubject", allEntries = true) // 清空缓存
    public R addOneSubject(@RequestBody SubjectNestedVo subject){
        subjectService.addOneSubject(subject);
        return R.ok();
    }
    
    // 删除课程分类
    @Schema(description = "删除课程分类")
    @PostMapping("deleteSubject/{id}")
    @CacheEvict(value = "eduSubject", allEntries = true) // 清空缓存
    public R deleteSubject(@PathVariable String id) {
        log.info("开始删除课程分类，ID: {}", id);
        try {
            boolean result = subjectService.removeSubjectById(id);
            if (result) {
                log.info("成功删除课程分类，ID: {}", id);
                return R.ok();
            } else {
                log.warn("删除课程分类失败，未找到该分类，ID: {}", id);
                return R.error().message("删除失败，未找到该分类");
            }
        } catch (Exception e) {
            log.error("删除课程分类时发生异常，ID: {}", id, e);
            return R.error().message("删除失败: " + e.getMessage());
        }
    }
}
